<script setup lang="ts">
import { dictionaryApi } from "@/api/admin/dictionary";
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElDialog,
  ElButton,
  ElMessage,
  // ElSelect,
  // ElOption,
  // ElRow,
  // ElCol,
} from "element-plus";
import { nextTick, ref } from "vue";

const isEditor = ref(false);
const visible = ref(false);

const dictionaryOptionsFormRef = ref<any>(null);

class DictionaryOptionsForm {
  id = undefined;
  label = "";
  value = "";
  dictionaryId = "";
}

const dictionaryOptionsForm = ref<any>(new DictionaryOptionsForm());

const emit = defineEmits(["update"]);

// 打开弹窗
const open = (dictionaryId: string, data: any = null) => {
  if (!dictionaryId) {
    return ElMessage.info("请选择字典");
  }
  visible.value = true;
  if (data) {
    // console.log(data);
    isEditor.value = true;
    nextTick(() => {
      dictionaryOptionsForm.value = data;
      dictionaryOptionsForm.value.dictionaryId = dictionaryId;
    });
  } else {
    dictionaryOptionsForm.value = new DictionaryOptionsForm();
    dictionaryOptionsForm.value.dictionaryId = dictionaryId;
    isEditor.value = false;
  }
};

// 清除表单数据
const clearForm = () => {
  dictionaryOptionsFormRef.value.resetFields();
};

const handleCancel = () => {
  clearForm();
  visible.value = false;
};

// 关闭弹窗
const handleClose = (deno: () => void) => {
  clearForm();
  deno();
};

const handleOk = async () => {
  await dictionaryOptionsFormRef.value.validate();
  let ret: any = null;
  ret = await dictionaryApi.saveDictionaryOptionsApi(dictionaryOptionsForm.value);
  if (ret.code === 200) {
    ElMessage.success(ret.msg);
    emit("update", dictionaryOptionsForm.value.menuId);
    handleCancel();
  } else {
    ElMessage.error(ret.data.msg);
  }
};

// 暴露方法
defineExpose({
  open,
});
</script>

<template>
  <el-dialog
    :title="isEditor ? '修改' : '新增'"
    :before-close="handleClose"
    v-model="visible"
  >
    <el-form
      ref="dictionaryOptionsFormRef"
      :model="dictionaryOptionsForm"
      label-position="right"
      label-width="70px"
    >
      <el-form-item
        prop="label"
        label="数据名称"
        :rules="[{ required: true, message: '请输入数据名称' }]"
      >
        <el-input v-model="dictionaryOptionsForm.label" placeholder="请输入数据名称" />
      </el-form-item>
      <el-form-item
        prop="value"
        label="数据值"
        :rules="[{ required: true, message: '请输入数据值' }]"
      >
        <el-input v-model="dictionaryOptionsForm.value" placeholder="请输入数据值" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleOk">
          {{ isEditor ? "提交修改" : "添加" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="less" scoped></style>
